# -*- coding: utf-8 -*-
from typing import Union, List, Optional
from fastapi import APIRouter, HTTPException , Request
from pydantic import BaseModel

from web.config.Logger import logger
from web.tdx.sever.RealTimeQuotes import RealTimeQuotes

testRouter = APIRouter()



@testRouter.get("/")
def read_root():
    return {"Hello": "World"}

"""

stockCode :股票编号-----如60036
frequency 取值: 0    1       2     3     4        5     6      7      8    9       10     11
             '5m', '15m', '30m', '1h', 'day', 'week', 'mon', '1m', '1m', 'day', '3mon', 'year'
offset: 返回的数据条数
start:距离今天或者当前前多少个交易日的数据
比如 frequency9， start0，offset2  返回的是当前交易日和上一个交易日的数据
"""
@testRouter.get("/kline")
def kline(stockCode: Union[str, None] = None,frequency: Union[int, None] = 0, offset: Union[int, None] = 10 ,start: Union[int, None] = 0,adjust: Union[str, None] = ''):

    client = RealTimeQuotes()
    data = client.bars(symbol=stockCode, frequency= frequency, start=start ,offset=offset,adjust =adjust)
    #print(data.to_string(header=True, sparsify=False))
    #str = data.to_json(orient='records', date_format='iso', date_unit='s')
    #logger.info(str)

    return {"data":data.to_dict(orient='records')}


@testRouter.get("/minute")
def minute(stockCode: Union[str, None] = None):
    client = RealTimeQuotes()
    data = client.minute(symbol=stockCode)

    return {"data":data.to_dict(orient='records')}


@testRouter.get("/minutes")
def minutes(stockCode: Union[str, None] = None, date: Union[str, None] = None):
    client = RealTimeQuotes()
    data = client.minutes(symbol=stockCode,date=date)
    return {"data":data.to_dict(orient='records')}



@testRouter.get("/ohlc")
def ohlc(stockCode: Union[str, None] = None,begin: Union[str, None] = "2011-01-25", end: Union[str, None] = "2025-7-11",adjust: Union[str, None] = ""):
    client = RealTimeQuotes()
    data = client.ohlc(symbol=stockCode, begin= begin, end=end, adjust=adjust)
    return {"data":data.to_dict(orient='records')}


@testRouter.get("/ohlcAllDay")
def ohlcAllDay(stockCode: Union[str, None] = None,begin: Union[str, None] = "1991-01-25", end: Union[str, None] = "2099-7-11",adjust: Union[str, None] = ""):
    client = RealTimeQuotes()
    data = client.ohlc(symbol=stockCode, begin= begin, end=end, adjust=adjust)
    return {"data":data.to_dict(orient='records')}

# 定义请求体模型
class StockCodesRequest(BaseModel):
    stockCodes: List[str]

"""
    当前股价信息
    stockCodes:股票集合

    post请求如：
    {
        "stockCodes": ["300168", "600036"]
    }
"""
@testRouter.post("/now")
def now(stock_codes_request: StockCodesRequest):

    if not stock_codes_request.stockCodes:
        raise HTTPException(status_code=400, detail="No stock codes provided")

    client = RealTimeQuotes()
    data = client.quotes(symbol=stock_codes_request.stockCodes)

    return {"data":data.to_dict(orient='records')}




@testRouter.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}
